<?
class YelpManager
{
	private $sid;
	private $searchResult;
	
	
  function __construct(){
    
  }
	public function  searchStore($param)
	{
		$this->sid = $param;
		$searchTerm="";
		$sql="select yelp_term from stores where active=1  and store_id=" . $this->sid;
		//echo $sql;
		//echo "<p>";
    $q = mysql_query($sql);
    $row = mysql_fetch_row($q);
    $searchTerm = $row[0];
    if($searchTerm == "")
      throw new Exception("Invalid StoreId");
    
    $this->searchResult =$this->executeSearch($searchTerm);
    
	}
	
public function  searchTerm($id, $searchTerm, $city)
  {
    $this->sid = $id;
    if(strlen($city) < 1)
      $city="Detroit";
    $this->searchResult = $this->executeSearch($searchTerm, $city);
    //var_dump($this->searchResult);
    echo "<p>";
  }
  
  private function executeSearch($searchTerm,  $city)
  {
  	$searchTerm = urlencode($searchTerm);
  	$yelpURL ="http://api.yelp.com/business_review_search?term=" 
                  . $searchTerm . 
                  "&location=" .  $city ."%20MI&radius=1&ywsid=DV-8c6B4AhUhsjTnz5aFPg"; 
    $curl = curl_init();
    curl_setopt ($curl, CURLOPT_URL, $yelpURL);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $result = curl_exec ($curl);
    curl_close ($curl);
    return json_decode($result, true);
  }
	public function isYelpRequest()
	{
		if(is_null($this->searchResult)){
			echo "Isnull<p>";
			return false;
		}
		
		if(count($this->searchResult) != 2){
			echo "isInvalid<p>";
			return false;
    }
      
    try{
    	if(is_array($this->searchResult["businesses"]))
    	  return true;
    }catch(Exeption $e){
    	echo "isWeird<p>";
    	return false;
    }
		 return true;
	}
	
	public function getText()
	{
		$sql="select 'Hello Database'";
		$q = mysql_query($sql);
		$row = mysql_fetch_row($q);
		return $row[0];
	}
	
	public function getStores()
	{
		if(!$this->isYelpRequest())
		  throw new Exception("Invalid call to YelpManager.getStore, Search did not execute or did not return results");

		 $result = array();
		 //var_dump(count($this->searchResult["businesses"]));
		for ($i = 0; $i < count($this->searchResult["businesses"]);$i++){
			$storeName =$this->searchResult["businesses"][$i]["name"] ;
			echo "Yelp StoreName: " . $storeName . "<br>"; 
			if($this->hasFilterMatch($storeName) && !$this->hasExcludeFilterMatch($storeName))
			{
				
        $yelpStore = new YelpStoreVO();
        $yelpStore->ratingImgUrl = $this->searchResult["businesses"][$i]["rating_img_url"];
        $yelpStore->id = $this->searchResult["businesses"][$i]["id"];
        $yelpStore->mobileURL= $this->searchResult["businesses"][$i]["mobile_url"];
        $yelpStore->ratingImgURLSmall = $this->searchResult["businesses"][$i]["rating_img_url_small"];
        $yelpStore->photoUrl = $this->searchResult["businesses"][$i]["photo_url"];
        $yelpStore->name = $this->searchResult["businesses"][$i]["name"];
        $yelpStore->url = $this->searchResult["businesses"][$i]["url"];
        $yelpStore->avgRating = $this->searchResult["businesses"][$i]["avg_rating"];
        $yelpStore->nearbyURL = $this->searchResult["businesses"][$i]["nearby_url"];
        $yelpStore->photoURLSmall = $this->searchResult["businesses"][$i]["photo_url_small"];
        //$yelpStore->snippetText = $this->searchResult["businesses"][$i]["snippet_ticket"];
        $yelpStore->reviews = $this->getReviews($i);
        array_push($result, $yelpStore);
			}
			
		}
		return $result;
	}
	
  private function getReviews($index)
  {
  	if(!$this->isYelpRequest())
      throw new Exception("Invalid call to YelpManager.getReviews, Search did not execute or did not return results");

    $result = array();
    if(! is_array($this->searchResult["businesses"][$index]["reviews"])){
    	
      return $result;
    }
    $ar = $this->searchResult["businesses"][$index]["reviews"];
    for($i=0;$i<count($ar);$i++){
      	//echo "<p>";
      	//var_dump($ar[$i]);
      	//echo "</p>";
      	$review = new YelpReviewVO();
      	$review->date = $ar[$i]["date"];
      	$review->excerpt= $ar[$i]["text_excerpt"];
      	$review->ratingImgURL= $ar[$i]["rating_img_url"];
      	$review->ratingImgURLSmall= $ar[$i]["rating_img_url_small"];
      	$review->rating= $ar[$i]["rating"];
      	$review->mobileURL= $ar[$i]["mobile_uri"];
      	$review->url= $ar[$i]["url"];
      	$review->userPhotoURL= $ar[$i]["user_photo_url"];
      	$review->userPhotoURLSmall = $ar[$i]["user_photo_url_small"];
      	$review->userURL= $ar[$i]["user_url"];
      	$review->userName= $ar[$i]["user_name"];
      	array_push($result, $review);
    }
    return $result;
  }
  
  public function saveStore($store)
  {
  	$this->saveYelpStore($store);
  	$this->saveReviews($store->id, $store->reviews);
  }
  
  private function saveYelpStore($store)
  {
  	/*
  	 * Query for name
  	 * if it exists update
  	 * else insert
  	 * 
  	 * return Id
  	 */ 
  	$sql="select count(*) from yelp_store where id='$store->id'";
  	$q = mysql_query($sql);
    $row = mysql_fetch_row($q);
    $count = $row[0];
    
    if($count ==0)
    {
    	// insert $this->sid
    	$sql=
    	"insert into yelp_store
			(
			id,
			store_id,
			name,
			mobile_url,
			distance,
			rating_img_url,
			rating_img_url_small,
			url,
			snippet_text,
			image_url,
			snippet_image_url,
			is_closed,
			country_code,
			city,
			review_count,
			zip,
			state,
			address1,
			address2,
			phone,
			state_code,
			photo_url,
			avg_rating,
			ountry,
			longitude,
			nearby_url,
			latitude,
			photo_url_small
			)
			values
			(
			'$store->id',
			'$this->sid',
			'" . mysql_real_escape_string($store->name) . "',
			'$store->mobileURL',
			'DISTANCE',
			'$store->ratingImgUrl',
			'$store->ratingImgURLSmall',
			'$store->url',
			'SNIPPETETX',
			'IMAGEURL',
			'SNIPPETIMAGEURL',
			'ISCLOSED',
			'CODE',
			'CITY',
			'CNT',
			'ZIP',
			'STATE',
			'ADDRESS',
			'ADDR2',
			'PHONE',
			'STATE',
			'$store->photoUrl',
			'$store->avgRating',
			'COUNTRY',
			'LONG',
			'$store->nearbyURL',
			'LAT',
			'$store->photoURLSmall')";
    	
    	
    }else{
    	//update
    	$sql=
    	"
    	update yelp_store
    	set name= '" . mysql_real_escape_string($store->name) . "',
    	mobile_url='$store->mobileURL',
      rating_img_url='$store->ratingImgUrl',
      rating_img_url_small='$store->ratingImgURLSmall',
      url='$store->url',
      photo_url='$store->photoUrl',
      avg_rating='$store->avgRating', 
      nearby_url='$store->nearbyURL', 
      photo_url_small='$store->photoURLSmall'
    	where id = '$store->id'";
    }
    echo "<p>insert Yelp Store<br>" .$store->name . "<p>";
    mysql_query($sql);
  }
  
  private function saveReviews($yelpStoreId, $ar)
  {
    /*
     * delete reviews per sid
     * insert new reviews per sid
     */	
  	 //mysql_query("delete from yelp_review where yelp_id = '$yelpStoreId'");
  	mysql_query("delete from yelp_review where store_id = '$this->sid'");
  	 for($i=0;$i<count($ar);$i++)
  	 {
  	 	//
  	 	$review = $ar[$i];
  	 $sql=	"insert into yelp_review
		(
		rating,
		excerpt,
		rating_image_small_url,
		rating_image_url,
		user_id,
		user_image_url,
		user_name,
		user_url,
		user_photo_url,
		user_photo_url_small,
		date, 
		store_id, 
		yelp_id
		)
		values
		(
		'$review->rating',
		'" . mysql_real_escape_string($review->excerpt) . "',
		'$review->ratingImgURLSmall',
		'$review->ratingImgURL',
		'userid',
		'user_image_url',
		'$review->userName',
		'$review->userURL',
		'$review->userPhotoURL',
		'$review->userPhotoURLSmall',
		'$review->date', 
		$this->sid,'$yelpStoreId')";
		//echo $sql;
		echo "<p>insert review<br>" . $review->excerpt . "<p>";
		mysql_query($sql);
  	 }
  }
  
  private function hasFilterMatch($s)
  {
  	$sql="select filter from result_filters where store_id =" . $this->sid;
    echo $sql;
    echo "<p>";
    $cnt =0;
    $q = mysql_query($sql);
    while($row = mysql_fetch_row($q))
    {
    	$cnt ++;
    	echo    "filter storeName: " . $s . " filter: " . $row[0] . " result: " . strpos(strtoupper($s),strtoupper($row[0])) .  "<br>";
    	if( ! is_numeric(strpos(strtoupper($s),strtoupper($row[0]))))
    	{
    		echo "Did not pass<br>";
    	  return false;
    	}
    }
  	
    echo "count : " . $cnt ."<br>";
  	if($cnt == 0)
  	  return false;
  	else
  	  return true;
  }
  
  private function hasExcludeFilterMatch($s)
  {
  	$sql="select filter from exclude_filter where store_id =" . $this->sid;
  	echo $sql;
  	echo "<p>Excldue Filer</br>";
  	$cnt =0;
  	$q = mysql_query($sql);
  	$hasMatch = false;
  	while($row = mysql_fetch_row($q))
  	{
  		$cnt ++;
  		echo    "storeName: " . $s . " filter: " . $row[0] . " result: " . strpos(strtoupper($s),strtoupper($row[0])) .  "<br>";
  		if( is_numeric(strpos(strtoupper($s),strtoupper($row[0]))))
  		{
  			echo "Did not pass<br>";
  			$hasMatch = true;
  			break;
  		}
  	}
  
  	return $hasMatch;
  }
}

?>